const urls = require('url');
const fs = require('fs');
const path = require('path');
//阿里联盟接口高佣转化，订单同步，获取订单详情，淘口令解码，淘口令加密
module.exports = class extends think.Service {
	constructor() {
		super();
		this.orders = [];
		let setup = think.config("setup");
		this.apiAppkey = setup.taokeAppkey;
		this.apiQQ = setup.taokeQQ;
		this.apiSpareAppkey = setup.taokeSpareAppkey;
		this.apiSpareTaobao = encodeURIComponent(setup.taokeSpareTaobao);
	}
	//通过cookie获取订单，不稳定，暂不使用xls
	async getExcelOrder() {
		try {
			let time = new Date().valueOf();
			let endDate = think.datetime(time).slice(0, 10);
			let startDate = think.datetime(time - 30 * 24 * 3600 * 1000).slice(0, 10);
			let setup = think.config("setup");
			let getOrderApi = `${setup.orderUpdateApi}?startTime=${startDate}&endTime=${endDate}&payStatus=&queryType=1&DownloadID=DOWNLOAD_REPORT_INCOME_NEW`;
			let data = {};
			let xlsname = path.join(think.ROOT_PATH, `/www/upload/excel/${new Date().valueOf()}.xls`);
			console.log(getOrderApi);
			data = await this.fetch(getOrderApi, {
				method: 'GET',
				headers: {
					'cookie': setup.taokeLoginCookie,
					'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'
				},
			});
			const xls = await fs.createWriteStream(xlsname);
			await data.body.pipe(xls);
			return xlsname;
		}
		catch(e) {
			console.log(e);
		}
	}
	//通过cookie获取订单，不稳定，暂不使用JSON
	async getJsonOrder(pageNum) {
		try {
			let time = new Date().valueOf();
			let endDate = think.datetime(time).slice(0, 10);
			let startDate = think.datetime(time - 30 * 24 * 3600 * 1000).slice(0, 10);
			let toPage = pageNum || 1;
			let setup = think.config("setup");
			let getOrderApi = `${setup.orderUpdateApi}?startTime=${startDate}&endTime=${endDate}&payStatus=&queryType=1&toPage=${toPage}&perPageSize=100&total=&t=${time}&pvid=&_tb_token_=ed05af34afeeb&_input_charset=utf-8`;
			let data = {};
			data = await this.fetch(getOrderApi, {
				method: 'GET',
				headers: {
					'cookie': setup.taokeLoginCookie,
					'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'
				},
			}).then(res => res.json());
			if(toPage == 1) {
				this.orders = [];
			}
			this.orders = this.orders.concat(data.data.paymentList);
			if(!data.data.hascount) {
				toPage++;
				await this.getJsonOrder(toPage);
			}
			return this.orders;
		}
		catch(e) {
			console.log(e);
		}
	}
	//第三方接口更新订单
	async getOrders(orderType, orderTime) {
		try {
			//更新订单，默认创建事件，可设置create_time、settle_time
			let channel = think.config('setup.taokeApiChannel');
			let orders = [];
			if(channel == 1 || channel == 4) {
				//orders = await this.getOrdersByApi(orderType, '', orderTime);
				orders = await this.getOrdersByTaobaoApi(orderType, '', orderTime);
			}
			if(channel == 2 || channel == 3) {
				await think.timeout(1800);
				orders = await this.getOrdersBySpareApi(orderType, '', orderTime);
			}
			return orders;
		}
		catch(e) {
			console.log(e);
		}
	}
	//通过第三方封装的接口调用订单
	async getOrdersByApi(orderType, pageNum, starttime) {
		try {
			let orderUrl = think.config('setup.taokeOrderUrl');
			
			let session = think.config('setup.taokeOrderSession');
			let time = new Date().valueOf();
			let startDate = starttime || think.datetime(time - 600 * 1000);
			let toPage = pageNum || 1;
			orderType = orderType || 'create_time';
			console.log(`${orderUrl}?start_time=${startDate}&page_no=${toPage}&page_size=30&tk_status=1&order_query_type=${orderType}&appkey=${this.apiAppkey}&qq=${this.apiQQ}&session=${session}`);
			let res = await this.fetch(`${orderUrl}?start_time=${startDate}&page_no=${toPage}&page_size=30&tk_status=1&order_query_type=${orderType}&appkey=${this.apiAppkey}&qq=${this.apiQQ}&session=${session}`).then(res => res.text());
			console.log(res);
			let data = JSON.parse(res.replace(/(\d{16,20})/g, "\"$&\""));
			
			if(toPage == 1) {
				this.orders = [];
			}
			if(!think.isEmpty(data.xiaocao.tbk_sc_order_get_response.results.n_tbk_order)) {
				this.orders = this.orders.concat(data.xiaocao.tbk_sc_order_get_response.results.n_tbk_order);
				if(data.xiaocao.tbk_sc_order_get_response.results.n_tbk_order.length == 30) {
					toPage++;
					await this.getOrdersByApi(orderType, toPage, startDate);
				}
			}
			console.log(this.orders);
			return this.orders;
		}
		catch(e) {
			console.log(e);
		}
	}
	async getOrdersBySpareApi(orderType, pageNum, starttime) {
		try {
			let orderUrl = think.config('setup.taokeSpareOrderUrl');
			let time = new Date().valueOf();
			let startDate = starttime || think.datetime(time - 600 * 1000);
			let toPage = pageNum || 1;
			orderType = orderType || 'create_time';
			console.log(`${orderUrl}?apkey=${this.apiSpareAppkey}&starttime=${encodeURIComponent(startDate).replace(/%20/g,'+')}&span=600&page=${toPage}&pagesize=100&tkstatus=1&ordertype=create_time&tbname=${this.apiSpareTaobao}`);
			let res = await this.fetch(`${orderUrl}?apkey=${this.apiSpareAppkey}&starttime=${encodeURIComponent(startDate).replace(/%20/g,'+')}&span=600&page=${toPage}&pagesize=100&tkstatus=1&ordertype=${orderType}&tbname=${this.apiSpareTaobao}`).then(res => res.json());
			console.log(res);
			//		let data = JSON.parse(res.replace(/(\d{16,20})/g, "\"$&\""));
			if(toPage == 1) {
				this.orders = [];
			}
			if(!think.isEmpty(res.data.n_tbk_order)) {
				this.orders = this.orders.concat(res.data.n_tbk_order);
				if(res.data.n_tbk_order.length == 100) {
					toPage++;
					await this.getOrdersBySpareApi(orderType, toPage, startDate);
				}
			}
			console.log(this.orders);
			return this.orders;
		}
		catch(e) {
			console.log(e);
		}
	}
	async getTaoword(info) {
		const topsdk = think.service("topsdk");
		const taoword = await topsdk.execute("taobao.tbk.tpwd.create", info);
		return taoword;
	}
	async queryTaoword(content) {
		const topsdk = think.service("topsdk");
		const data = await topsdk.execute("taobao.wireless.share.tpwd.query", {
			'password_content': content
		});
		console.log("9999999999999999999")
		return data;
	}
	//根据商品ID获取商品详情
	async getDetail(id) {
		const topsdk = think.service("topsdk");
		const data = await topsdk.execute("taobao.tbk.item.info.get", {
			'fields': 'num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url',
			'platform': '2',
			'num_iids': id.toString()
		});
		console.log(data);
		console.log("8888888888888888888");
		if(think.isEmpty(data.results)) {
			return false;
		}
		console.log(data.results.n_tbk_item[0])
		return data.results.n_tbk_item[0];
	}
	async getCoupon(me) {
		const topsdk = think.service("topsdk");
		const data = await topsdk.execute("taobao.tbk.coupon.get", {
			'me': me
		});
		return data;
	}
	async transferLink(id) {
		let channel = think.config('setup.taokeApiChannel');
		let data = {};
		if(channel == 1 || channel == 3) {
			//data = await this.transferLinkByApi(id);
			data = await this.transferLinkByTaobaoApi(id);
		}
		if(channel == 2 || channel == 4) {
			data = await this.transferLinkBySpareApi(id);
		}
		return data;
	}
	async transferLinkByApi(id) {
		try {
			let url = think.config('setup.taokeVipUrl');
			let token = think.config('setup.taokeVipToken');
			let pid = think.config('setup.taokeVipPid');
			let res = await this.fetch(url, {
				method: 'POST',
				body: `token=${token}&item_id=${id}&adzone_id=${pid.split("_")[3]}&site_id=${pid.split("_")[2]}&qq=${this.apiQQ}`,
				headers: {
					'Content-Type': "application/x-www-form-urlencoded"
				},
				responseType: 'json'
			}).then(res => res.json());
			console.log(res);
			return res.result.data;
		}
		catch(e) {
			console.log(e);
		}
	}
	async transferLinkBySpareApi(id) {
		try {
			let url = think.config('setup.taokeSpareVipUrl');
			let pid = think.config('setup.taokeVipPid');
			console.log(`${url}?apkey=${this.apiSpareAppkey}&itemid=${id}&pid=${pid}&tbname=${this.apiSpareTaobao}`)
			let res = await this.fetch(`${url}?apkey=${this.apiSpareAppkey}&itemid=${id}&pid=${pid}&tbname=${this.apiSpareTaobao}`).then(res => res.json());
			console.log(res);
			return res.result.data;
		}
		catch(e) {
			console.log(e)
		}
	}
	//从带淘口令的信息/查询网址中获取商品ID
	async goodsId(info) {
		try {
			let goodsId = "";
			const taokeSplit = `[${think.config("setup.taokeSplit")}]{1}`;
			let reg = new RegExp(taokeSplit + "[0-9a-zA-Z]{6,30}" + taokeSplit);
			console.log(reg);
			let goodsUrl = "";
			if(info.match(reg)) {
				let tpwd = await this.queryTaoword(info);
				console.log(tpwd);
				if(think.isEmpty(tpwd.url)) {
					return false;
				}
				let goodsId = '';
				if(tpwd.url.match(/item_id=[0-9]+(&)?/)) {
					goodsId = (tpwd.url.match(/item_id=[0-9]+(&)?/)[0]).match(/[0-9]+/)[0]
					return goodsId;
				}
				if(tpwd.url.match(/&id=[0-9]+(&)?/)) {
					goodsId = (tpwd.url.match(/&id=[0-9]+(&)?/)[0]).match(/[0-9]+/)[0]
					return goodsId;
				}
				goodsUrl = tpwd.url;
			}
			else if(info.match(/id=[0-9]+(&)?/)) {
				let goodsId = (info.match(/id=[0-9]+(&)?/)[0]).match(/[0-9]+/)[0]
				return goodsId;
			}
			else if(info.match(/喵口令/) && info.match(/(http|https):[a-zA-Z0-9./?=]+/)) {
				let url = info.match(/(http|https):[a-zA-Z0-9./?=]+/);
				let data = await this.fetch(url[0]).then(res => res.text());
				if(think.isEmpty(data.match(/pageData[^;]+\};/))) {
					return false;
				}
				let json = data.match(/pageData[^;]+\};/)[0].slice(11);
				let result = JSON.parse(json.slice(0, -1));
				goodsId = result.bizId;
				return goodsId;
			}
			else {
				let url = info.match(/(http|https):[a-zA-Z0-9./?=]+/);
				let data = await this.fetch(url[0]).then(res => res.text());
				console.log(data)
				if(think.isEmpty(data.match(/var\surl\s=\s\'http[^']+/)[0])) {
					return false;
				}
				goodsUrl = data.match(/var\surl\s=\s\'http[^']+/)[0].match(/(http|https)[^']+/)[0];
			}
			let url = "";
			if(goodsUrl.match(/https:[a-z\./]+[0-9]+\.htm/)) {
				url = goodsUrl.match(/https:[a-z\./]+[0-9]+\.htm/)[0];
			}
			else {
				let data = await this.fetch(goodsUrl).then(res => res.text());
				console.log(data)
				url = data.match(/https:[a-z\./]+[0-9]+\.htm/)[0];
			}
			goodsId = url.match(/[0-9]+/)[0];
			return goodsId;
		}
		catch(e) {
			console.log(e);
			return false;
		}
	}
	async search(q, cat, sort, page_size, page_no) {
		const topsdk = think.service("topsdk");
		const data = await topsdk.execute("taobao.tbk.dg.material.optional", {
			'adzone_id': 177194768,
			'q': q,
			'cat': cat || '',
			'sort': sort || '',
			'platform': 2,
			'page_size': page_size || 20,
			'page_no': page_no || 1
		});
		return data;
	}
	//直接调接口
	async getOrdersByTaobaoApi(orderType, pageNum, starttime) {
		try {
			let session = think.config('setup.alimamaVipSession');
			let time = new Date().valueOf();
			let startDate = starttime || think.datetime(time - 600 * 1000);
			let toPage = pageNum || 1;
			orderType = orderType || 'create_time';
			const topsdk = think.service("topsdk", {
				appkey: think.config('setup.alimamaVipAppid'),
				appsecret: think.config('setup.alimamaVipSecret')
			});
			const data = await topsdk.execute("taobao.tbk.sc.order.get", {
				'session': session,
				'fields': 'relation_id,tb_trade_parent_id,tb_trade_id,num_iid,item_title,item_num,price,pay_price,seller_nick,seller_shop_title,commission,commission_rate,unid,create_time,earning_time,tk3rd_pub_id,tk3rd_site_id,tk3rd_adzone_id,special_id,click_time,tk_status',
				'start_time': startDate,
				'span': 600,
				"page_no": toPage,
				"page_size": 100,
				"tk_status": 1,
				"order_query_type": orderType
			});
			
			if(toPage == 1) {
				this.orders = [];
			}
			if(!think.isEmpty(data.results.n_tbk_order)) {
				this.orders = this.orders.concat(data.results.n_tbk_order);
				if(data.results.n_tbk_order.length == 100) {
					toPage++;
					await this.getOrdersByTaobaoApi(orderType, toPage, startDate);
				}
			}
			return this.orders;
		}
		catch(e) {
			console.log(e);
		}
	}
	async transferLinkByTaobaoApi(id) {
		try {
			let session = think.config('setup.alimamaVipSession');
			let pid = think.config('setup.taokeVipPid');
			const topsdk = think.service("topsdk", {
				appkey: think.config('setup.alimamaVipAppid'),
				appsecret: think.config('setup.alimamaVipSecret')
			});
			const data = await topsdk.execute("taobao.tbk.privilege.get", {
				'session': session,
				'item_id': id,
				'adzone_id': pid.split("_")[3],
				'platform': '1',
				'site_id': pid.split("_")[2]
			});
			return data.result.data;
		}
		catch(e) {
			console.log(e);
		}
	}
	
	async refreshSession(){
		let appkey = think.config('setup.alimamaVipAppid');
		let appsecret = think.config('setup.alimamaVipSecret');
		let session = think.config('setup.alimamaVipSession');
		let refreshToken = think.config('setup.alimamaVipToken');
		let sign = think.md5("appkey"+appkey+"refresh_token"+refreshToken+"sessionkey"+session+appsecret).toUpperCase();
		let refreshUrl = "http://container.api.taobao.com/container/refresh?appkey="+appkey+"&refresh_token="+refreshToken+"&sessionkey="+session+"&sign="+sign;
		let data = await this.fetch(refreshUrl).then(res => res.json());
		return data;
	}
	
}